using System;
using System.IO;
using System.Linq;
using System.Windows.Media.Imaging;
using Legacy.Core.SaveGameManagement;

namespace MMXSaveGameConverter
{
    internal sealed class XmlFileReader : FileReaderBase
    {
        private readonly string _xmlPath;

        public XmlFileReader(string savePath)
        {
            _xmlPath = savePath;
        }

        public override IReaderState Read()
        {
            return new XmlReadState(_xmlPath);
        }

        public override SaveFileMeta ReadFileMeta(IReaderState readerState)
        {
            XmlReadState state = (XmlReadState)readerState;
            if (state.FileMetaReaded)
                throw new InvalidOperationException();

            state.FileMetaReaded = true;

            return SaveFileMeta.FromXml(state.XmlDocument);
        }

        public override SaveGameMeta ReadSaveMeta(IReaderState readerState)
        {
            XmlReadState state = (XmlReadState)readerState;
            if (!state.FileMetaReaded || state.SaveMetaReaded)
                throw new InvalidOperationException();

            state.SaveMetaReaded = true;

            return Xml2Save.GetSaveMeta(state.XmlDocument);
        }

        public override SaveGame ReadSaveGame(IReaderState readerState, SaveGameMeta saveMeta)
        {
            XmlReadState state = (XmlReadState)readerState;
            if (!state.FileMetaReaded || !state.SaveMetaReaded || state.SaveGameReaded)
                throw new InvalidOperationException();

            state.SaveGameReaded = true;

            return Xml2Save.GetSaveGame(state.XmlDocument, saveMeta);
        }

        public override BitmapFrame ReadScreenshot(IReaderState readerState)
        {
            XmlReadState state = (XmlReadState)readerState;
            if (!state.FileMetaReaded || !state.SaveMetaReaded || !state.SaveGameReaded || state.ScreenshotReaded)
                throw new InvalidOperationException();

            state.ScreenshotReaded = true;

            using (FileStream input = File.OpenRead(Path.ChangeExtension(_xmlPath, ".png")))
            {
                PngBitmapDecoder decoder = new PngBitmapDecoder(input, BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.OnLoad);
                return decoder.Frames.First();
            }
        }
    }
}